package cn.donting.jme.utile.savable;

import com.jme3.export.JmeExporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class TxtJmeExporter implements JmeExporter {

    private HashMap<Integer, TxtOutputCapsule> idOutputCapsules;
    private HashMap<Savable, TxtOutputCapsule> savableOutputCapsule;
    private int id = 0;

    public TxtJmeExporter() {
        idOutputCapsules = new HashMap<>();
        savableOutputCapsule = new HashMap<>();

    }

    @Override
    public void save(Savable object, OutputStream f) throws IOException {

    }

    @Override
    public void save(Savable object, File f) throws IOException {
        object.write(this);
        String text = toText();
        System.out.println(text);
    }

    public String save(Savable object) throws IOException {
        object.write(this);
        String text = toText();
        return text;
    }

    @Override
    public TxtOutputCapsule getCapsule(Savable object) {
        TxtOutputCapsule outputCapsule = savableOutputCapsule.get(object);
        if (outputCapsule == null) {
            final int id = this.id++;
            outputCapsule = new TxtOutputCapsule(this, object, id);
            savableOutputCapsule.put(object, outputCapsule);
            idOutputCapsules.put(id, outputCapsule);
            try {
                object.write(this);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return outputCapsule;
    }

    private String toText() {
        StringBuilder txt = new StringBuilder();
        List<Integer> ids = idOutputCapsules.keySet().stream().sorted(Integer::compareTo).collect(Collectors.toList());
        for (Integer id : ids) {
            TxtOutputCapsule txtOutputCapsule = idOutputCapsules.get(id);
            txtOutputCapsule.toTxt(txt);
            txt.append("\n");
        }
        return txt.toString();
    }
}
